<template>
  <view class="container">
    <text class="title">系统登录</text>
    <input class="input-field" v-model="username" placeholder="请输入用户名" />
    <input class="input-field" v-model="password" type="password" placeholder="请输入密码" />
    <button class="login-button" @click="handleLogin">登录</button>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { api } from '@/services/api'

const username = ref('testuser')
const password = ref('123456')

const handleLogin = async () => {
  if (!username.value || !password.value) {
    uni.showToast({ title: '请输入用户名和密码', icon: 'none' })
    return
  }
  try {
    const resp: any = await api.login({ username: username.value, password: password.value })
    console.log('login result =', resp)
    // const resp:any = await api.login({ username: username.value, password: password.value })
    // const body = resp?.data ?? resp
    // uni.setStorageSync('SID', body.sessionId)
    // uni.setStorageSync('USER', body.user)
    //
    // console.log('login resp =', body)
    // console.log('saved SID =', uni.getStorageSync('SID'))

    // const sid = resp.data.sessionId;
    // localStorage.setItem('sid', sid);

    const sid = resp?.sessionId
    if (!sid) {
      throw new Error('后端未返回 sessionId，实际返回：' + JSON.stringify(resp))
    }
    localStorage.setItem('sid', sid)

    uni.switchTab({ url: '/pages/home/index' }) // 或你的首页路径

    // // 兼容可能的返回结构
    // const user = resp?.data ?? resp
    // uni.setStorageSync('USER', user)
    // uni.setStorageSync('LOGGED_IN', '1')

    uni.showToast({ title: `登录成功，欢迎 ${resp?.user?.username ?? ''}`, icon: 'success' })

    // 保存token
    // const raw = res?.data?.token ?? res?.data?.accessToken ?? res?.token;
    // if (!raw) {
    //   uni.showToast({ icon: 'none', title: '登录返回缺少token' });
    //   return;
    // }
    // const bearer = raw.startsWith('Bearer ') ? raw : `Bearer ${raw}`;
    // uni.setStorageSync('TOKEN', bearer);   // 关键：key 用 'TOKEN'，值含 Bearer

    // ⚠️ 你配置了 tabBar，因此用 switchTab（不要 navigateTo）
    uni.switchTab({ url: '/pages/home/index' })
  } catch (e) {
    console.error('登录失败:', e)
    uni.showToast({ title: '登录失败，请检查用户名或密码', icon: 'none' })
  }
}
</script>


<style>
.container { padding: 40px; }
.title { font-size: 24px; text-align: center; margin-bottom: 30px; }
.input-field { width: auto; height: 44px; border: 1px solid #e0e0e0; border-radius: 5px; padding: 0 10px; margin-bottom: 20px; }
.login-button { width: 100%; }
</style>